package edu.dayu.controller;

import edu.dayu.dao.EsObjectDao;
import edu.dayu.pojo.Activity;
import edu.dayu.pojo.Article;
import edu.dayu.util.Result;
import edu.dayu.vo.EsObject;
import org.elasticsearch.index.query.MultiMatchQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;


@RestController
@CrossOrigin
public class ESController {

    @Autowired
    EsObjectDao esObjectDao;


    @PostMapping("/esObjectSearch")
    public Result esObjectSearch(@RequestParam(value = "text",required = false) String text,
                                 @RequestParam(value = "pageNum") Integer pageNum,
                                 @RequestParam(value = "pageSize") Integer pageSize){
        Iterable<EsObject> esObjects;
        Pageable page = PageRequest.of(pageNum-1, pageSize);
        if (text !=null && !text.equals("")){
            MultiMatchQueryBuilder multiMatchQueryBuilder = QueryBuilders.multiMatchQuery(text, "name", "content", "link","type");
            esObjects = esObjectDao.search(multiMatchQueryBuilder,page);
        }else {
            esObjects = esObjectDao.findAll(page);
        }
        return Result.ok(esObjects);
    }
}
